//
//  MainViewController.swift
//  RuiLinWeibo
//
//  Created by Caesar on 15/10/8.
//  Copyright © 2015年 Caesar. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController{

    override func viewDidLoad() {
        super.viewDidLoad()
        
        addChildViewControllers()
        
        print(tabBar.subviews) // 此时 tabBarButton 还没有创建
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidDisappear(animated)
        
         setupComposeButton() // 此时 tabBarButton 都已经创建
    }
    
    // 运行循环监听事件后, 想 vc 发送消息, 动态执行方法, 因此不能设置 private
    // private 受保护的,只能在本类使用,不能被外界调用
    func clickComposeButton() {
        print(__FUNCTION__)
    }
    
    // 设置撰写按钮的位置 fame
    private func setupComposeButton(){
        let w = tabBar.bounds.width / CGFloat(viewControllers!.count)
        
        let rect = CGRect(x: 0, y: 0, width: w, height: tabBar.bounds.height)
        composeButton.frame = CGRectOffset(rect, 2 * w, 0)
    }

    
    // 添加所有控制器
    private func addChildViewControllers() {
        // 只是添加控制器,
        addChildViewController(HomeTableViewController(), title: "首页", imageNamed: "tabbar_home")
        
        addChildViewController(MessageTableViewController(), title: "消息", imageNamed: "tabbar_message_center")
        
        addChildViewController(UIViewController())
            
        addChildViewController(DiscoverTableViewController(), title: "发现", imageNamed: "tabbar_discover")
            
        addChildViewController(ProfileTableViewController(), title: "我", imageNamed: "tabbar_profile")
    }

    // 添加子控制器
    private func addChildViewController(vc:UIViewController, title:String, imageNamed:String) {
        
        //print(tabBar.subviews)
        
        //title 属性会从内向外传递
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageNamed)
        
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)

    }

    // 懒加载控件
    lazy private var composeButton: UIButton = {
        //自定义类型的按钮
        let button = UIButton()
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)

        self.tabBar.addSubview(button)
        
        button.addTarget(self, action: "clickComposeButton", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()

}
